<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../api/index.js"
import { checkblank, checkprice } from "../util/util.js";

const tableData = ref([]);
const checkObj = ref({
    page: 1,
    size: 10,
})
const total = ref({});

const addWinVisible = ref(false);
const addObj = ref({});

const editWinVisible = ref(false);
const editObj = ref({});
var editIndext = -1;

const formRef = ref({});


const uploadImgWinVisible = ref(false);
var imageUrl = ref({});//上传图片绑定的数据


//可选的设施类型
var typeOpt = ref([]);
var typeOptS = ref([]);

//可选的设施状态
const statusOpt = [
    {
        value: '正常',
        label: '正常',
    },
    {
        value: '损坏',
        label: '损坏',
    },
    {
        value: '维护中',
        label: '维护中',
    },
]
const statusOptS = [
    {
        value: '',
        label: '无', // 表示不筛选具体类型
    },
    ...statusOpt,

]

const getTypeOpt = async function () {
    let resultA = await api.get("api/attracts/type");
    typeOpt.value = resultA.data;
    typeOptS.value = [{ id: null, type: "无" }, ...typeOpt.value];
}

//显示数据
onMounted(async function () {
    //读取可选的类型
    getTypeOpt();
    checkData();
});

const checkData = async function (val) {
    if (typeof val == "number") {
        checkObj.value.page = val;
    }
    let result = await api.get("/api/attracts", checkObj.value);
    //更新表格中的数据
    tableData.value = result.data.res;
    total.value = result.data.count;
};

//检查表单填写的金额
const rules = reactive({
    fee: [{ validator: checkprice, trigger: "blur" }],
    name:[{validator:checkblank,trigger:"blur"}],
})



//添加数据
//显示窗口
const addWin = async function () {
    addWinVisible.value = true;
    addObj.value = {};
}
//保存添加的数据
const addSave = async function () {
    formRef.value.validate(
        async (valid) => {
            if (valid) {
                await api.postjson("/api/attracts", addObj.value);
                checkData();
                addWinVisible.value = false;
                ElMessage({
                    type: 'success',
                    message: '添加成功',
                });
            } else {
                console.log("添加失败");
            }
        }
    )
}

//删除数据
const del = function (index, row) {
    ElMessageBox.confirm(
        "确认删除？",
        "注意",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }).then(async function () {
            let result = await api.del("/api/attracts", row.id);
            if (result.code == 200) {
                tableData.value.splice(index, 1);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            } else {
                ElMessage({
                    type: 'info',
                    message: result.message
                })
            }
        }).catch(function () {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        });
}

//修改数据
const edit = function (index, row) {
    //记录修改数据的下标
    editIndext = index;
    //绑定要修改的数据
    editObj.value.id = row.id;
    editObj.value.name = row.name;
    if(row.attractsType){editObj.value.typeId=row.attractsType.id;}
    editObj.value.status = row.status;
    editObj.value.description = row.description;
    editObj.value.fee = row.fee;
    //打开对话框
    editWinVisible.value = true;
}
const editSave = async function () {
    formRef.value.validate(
        async (valid) => {
            if (valid) {
                await api.putjson("/api/attracts", editObj.value);
                checkData();
                editWinVisible.value = false;
                ElMessage({
                    type: 'success',
                    message: '修改成功',
                });
            } else {
                console.log("修改失败");
            }
        }
    )
}


const uploadimg = function (index, row) {
    uploadImgWinVisible.value = true;
    //imageUrl.value=row.description;
    // //显示已经上传的图片
     editIndext = index;
     editObj.value = { ...row }; // 使用扩展运算符创建 row 的一个副本
     imageUrl.value= row.description;
     console.log(imageUrl.value);

}

const handleAvatarSuccess = function (result, uploadFile) {
    console.log(result.data);
    imageUrl.value = result.data;
}
const beforeAvatarUpload = function () { }
const saveImage = async function () {
    //将文件的地址和数据发送到后台保存
    editObj.value.description = imageUrl.value;
    console.log(editObj.value);
    let result = await api.putjson("/api/attractsimg", editObj.value)

    // 手动更新表格中的数据
    tableData.value[editIndext] = { ...editObj.value };

    uploadImgWinVisible.value=false;
    ElMessage({
        type: 'success',
        message: '图片上传并更新成功',
    });
}

</script>
<template>
    <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="4"><el-input v-model="checkObj.name" style="width: 100%" placeholder="设施名称" /></el-col>
        <el-col :span="4">
            <el-select v-model="checkObj.typeId" placeholder="设施类型" style="width: 100%">
                <el-option v-for="item in typeOptS" :label="item.type" :value="item.id" />
            </el-select></el-col>
        <el-col :span="4">
            <el-select v-model="checkObj.status" placeholder="设施状态" style="width: 100%">
                <el-option v-for="item in statusOptS" :label="item.label" :value="item.value" />
            </el-select></el-col>
        <el-col :span="4"><el-button type="primary" @click="checkData" style="width: 100%;">
                <el-icon style="vertical-align: middle">
                    <Search />
                </el-icon>
                <span style="vertical-align: middle"> 搜索 </span>
            </el-button></el-col>
        <el-col :span="4" :offset="4"><el-button type="primary" @click="addWin" style="width: 100%;">
                <el-icon>
                    <CirclePlusFilled />
                </el-icon>
                <span style="vertical-align: middle"> 新增 </span>
            </el-button></el-col>
    </el-row>
    <div style="height: 500px; overflow: auto; margin-bottom: 20px;
        border-radius: 10px; /* 圆角半径 */
        margin-top: 20px; /* 上方间距 */
        padding: 10px; /* 内间距，确保内容不会紧贴边缘 */
        background-color: #fff; /* 可选：设置背景颜色 */
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 可选：添加阴影以提高视觉效果 */">
        <el-table :data="tableData" style="width: 100%;">
            <el-table-column prop="name" label="名称" min-width="80" />
            <el-table-column prop="attractsType.type" label="设施类型" min-width="80" />
            <el-table-column prop="status" label="设施状态" min-width="80" />
            <el-table-column prop="fee" label="建造成本" min-width="80" />
            <el-table-column prop="description" label="图片" min-width="100">
                <template #default="scope">
                    <el-image style="width: 100px; height: 100px;" :src="'api'+scope.row.description" :fit="contain"/>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button-group>
                    <el-button type="primary" @click="uploadimg(scope.$index, scope.row)">
                        <el-icon><Picture /></el-icon>
                        <span style="vertical-align: middle"> 图片 </span>
                    </el-button>
                    <el-button type="primary" @click="edit(scope.$index, scope.row)">
                        <el-icon>
                            <Edit />
                        </el-icon>
                        <span style="vertical-align: middle"> 编辑 </span>
                    </el-button>
                    <el-button type="danger" @click="del(scope.$index, scope.row)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </el-button-group>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <el-pagination background layout="prev, pager, next" :total="total" @current-change="checkData"
        :page-size="checkObj.size"
        style="position: fixed; left: 50%; transform: translateX(-50%); bottom: 100px; z-index: 1000;" />

    <!--start 新增信息的弹出框 -->
    <el-dialog v-model="addWinVisible" title="添加设施" width="500">
        <el-form :model="addObj" label-width="80px" :rules="rules" ref="formRef">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="addObj.name" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="设施类型" >
                        <el-select v-model="addObj.typeId" placeholder="Select" style="width: 100%;" >
                            <el-option v-for="item in typeOpt" :label="item.type" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="设施状态">
                        <el-select v-model="addObj.status" placeholder="Select" style="width: 100%;">
                            <el-option v-for="item in statusOpt" :label="item.name" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="建造成本" prop="fee">
                        <el-input v-model="addObj.fee" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="24">
                    <el-form-item label="简介">
                        <el-input v-model="addObj.description" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addWinVisible = false">取消</el-button>
                <el-button type="primary" @click="addSave">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end -->

    <!--start 修改信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="添加设施" width="500">
        <el-form :model="editObj" label-width="80px" :rules="rules" ref="formRef">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="名称">
                        <el-input v-model="editObj.name" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="设施类型">
                        <el-select v-model="editObj.typeId" placeholder="Select" style="width: 100%;">
                            <el-option v-for="item in typeOpt" :label="item.type" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="设施状态">
                        <el-select v-model="editObj.status" placeholder="Select" style="width: 100%;">
                            <el-option v-for="item in statusOpt" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="建造成本" prop="fee">
                        <el-input v-model="editObj.fee" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="24">
                    <el-form-item label="简介">
                        <el-input v-model="editObj.description" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editWinVisible = false">取消</el-button>
                <el-button type="primary" @click="editSave">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end -->

    <!--start 上传图弹出框-->
    <el-dialog v-model="uploadImgWinVisible" title="上传图片" width="500">
        <el-upload class="avatar-uploader" action="/api/uploadimg" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="'api'+imageUrl" class="avatar" :fit="contain"/>
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="saveImage">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end-->

</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>